package com.tulele.vtool.handler;

import com.tulele.vtool.bus.model.DailyPaperInfo;
import com.tulele.vtool.bus.model.UserInfo;
import com.tulele.vtool.bus.model.log.PushDetailLog;
import com.tulele.vtool.bus.service.IUserService;
import com.tulele.vtool.bus.service.IUserVipValidService;
import com.tulele.vtool.bus.service.SysGzhService;
import com.tulele.vtool.bus.service.UserGroupGzhService;
import com.tulele.vtool.model.PlatformSysInfo;
import com.tulele.vtool.model.UserGroupOpenId;
import com.tulele.vtool.task.async.*;
import com.tulele.vtool.util.RedisCacheUtil;
import com.tulele.vtool.util.SysConstant;
import com.tulele.vtool.wechat.service.WeixinService;
import com.tulele.vtool.wechat.service.WeixinServiceDL;
import com.tulele.vtool.wechat.service.WeixinServiceMap;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.bean.kefu.WxMpKefuMessage;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateData;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.util.Date;

@Slf4j
@RestController
public class TestHandler {

    @Autowired
    private FirstTimeArticlePushAsyncTask firstTimeArticlePushAsyncTask;

    @Autowired
    private SecondTimeArticlePushAsyncTask secondTimeArticlePushAsyncTask;

    @Autowired
    private ThirdTimeArticlePushAsyncTask thirdTimeArticlePushAsyncTask;

    @Autowired
    private ForthTimeArticlePushAsyncTask forthTimeArticlePushAsyncTask;

    @Autowired
    private FifthTimeArticlePushAsyncTask fifthTimeArticlePushAsyncTask;

    @Autowired
    private UserOperateDataPushAsyncTask userOperateDataPushAsyncTask;

    @Autowired
    private KefuMsgExpiredRemindAsyncTask kefuMsgExpiredRemindAsyncTask;

    @Autowired
    private RedisCacheUtil redisCacheUtil;

    @Autowired
    private IUserService userService;

    @Autowired
    private WeeklyTempMsgAsyncTask weeklyTempMsgAsyncTask;

    @Autowired
    private ExpirationReminderTempMsgAsyncTask expirationReminderTempMsgAsyncTask;

    @Autowired
    private RenewalReminderTempMsgAsyncTask renewalReminderTempMsgAsyncTask;

    @Autowired
    private IUserVipValidService userVipValidService;

    @Autowired
    private CommissionDeductionMsgAsyncTask commissionDeductionMsgAsyncTask;

    @Autowired
    private SixthTimeArticleMsgAsyncTask sixthTimeArticleMsgAsyncTask;

    @Autowired
    private NewUserMsgAsyncTask newUserMsgAsyncTask;

    @Autowired
    private UserDailyBrandSetInfoPushAsyncTask userDailyBrandSetInfoPushAsyncTask;

    @Autowired
    private DailyPaperTempMsgAsyncTask dailyPaperTempMsgAsyncTask;

    @Autowired
    private MsgAsync20210327Task msgAsync20210327Task;

    @Autowired
    private UploadTempMsgPushAsyncTask uploadTempMsgPushAsyncTask;

    @Autowired
    private UploadTempMsgPushAsync430Task uploadTempMsgPushAsync430Task;

    @Autowired
    private UserGroupGzhService userGroupGzhService;

//    @Value("${spring.application.name}")
//    private String springProfilesActive;

    @Autowired
    private SysGzhService sysGzhService;

    @Value("${Professional}")
    private String professional;//专业号

    @PostMapping(value = "/testFirstTime", produces = "application/json;charset=UTF-8")
    public String testFirstTime(@RequestHeader("userId") String userId, @RequestHeader("profile") String profile) throws Exception {
        //String nickName = this.userService.queryUserInfo(Integer.valueOf(userId)).getNickName();
        log.error("*********testFirstTime userId:" + userId);
        UserInfo userInfo = userService.queryUserInfo(Integer.valueOf(userId));
        firstTimeArticlePushAsyncTask.execute("wxPushUser" + userId, 0, userInfo, profile);
        return "testFirstTime调用完成";
    }

    @PostMapping(value = "/testSecondTime", produces = "application/json;charset=UTF-8")
    public String testSecondTime(@RequestHeader("userId") String userId, @RequestHeader("profile") String profile) throws Exception {
        UserInfo userInfo = userService.queryUserInfo(Integer.valueOf(userId));
        secondTimeArticlePushAsyncTask.execute("wxPushUser" + userId, 0, userInfo, profile);
        return "testSecondTime调用完成";
    }

    @PostMapping(value = "/testThirdTime", produces = "application/json;charset=UTF-8")
    public String testThirdTime(@RequestHeader("userId") String userId, @RequestHeader("profile") String profile) throws Exception {
        UserInfo userInfo = userService.queryUserInfo(Integer.valueOf(userId));
        thirdTimeArticlePushAsyncTask.execute("wxPushUser" + userId, 0, userInfo, profile);
        return "testThirdTime调用完成";
    }

    @PostMapping(value = "/testForthTime", produces = "application/json;charset=UTF-8")
    public String testForthTime(@RequestHeader("userId") String userId, @RequestHeader("profile") String profile) {
        UserInfo userInfo = userService.queryUserInfo(Integer.valueOf(userId));
        forthTimeArticlePushAsyncTask.execute("wxPushUser" + userId, 0, userInfo, profile);
        return "testForthTime调用完成";
    }

    @PostMapping(value = "/testFifthTime", produces = "application/json;charset=UTF-8")
    public String testFifthTime(@RequestHeader("userId") String userId, @RequestHeader("profile") String profile) throws Exception {
        UserInfo userInfo = userService.queryUserInfo(Integer.valueOf(userId));
        fifthTimeArticlePushAsyncTask.execute("wxPushUser" + userId, 0, userInfo, profile);
        return "testFifthTime调用完成";
    }

    @PostMapping(value = "/testSixthTime", produces = "application/json;charset=UTF-8")
    public String testSixthTime(@RequestHeader("userId") String userId, @RequestHeader("profile") String profile) throws WxErrorException {
//        log.error("*********testSixthTime userId:"+userId);
        UserInfo userInfo = userService.queryUserInfo(Integer.valueOf(userId));
//
//        if (professional.contains(profile)) {//专业号
//            sixthTimeArticleMsgAsyncTask.executeProfessional("wxPushUser" + userId, userInfo, 1, profile);
//        } else {
            sixthTimeArticleMsgAsyncTask.execute20210208("wxPushUser" + userId, userInfo, 1, profile);
//        }
        return "testSixthTime调用完成";
    }

    @PostMapping(value = "/test1710Time", produces = "application/json;charset=UTF-8")
    public String test1710Time(@RequestHeader("userId") String userId, @RequestHeader("profile") String profile) throws Exception {
        UserInfo userInfo = userService.queryUserInfo(Integer.valueOf(userId));
//        if (professional.contains(profile)) {//专业号
//            userOperateDataPushAsyncTask.executeProfessional("wxPushUser" + userId,userInfo, 1, profile);
//        } else {
            userOperateDataPushAsyncTask.execute20210208("wxPushUser" + userId, userInfo,1, profile);
//        }
        return "OK";
    }

    @PostMapping(value = "/test930", produces = "application/json;charset=UTF-8")
    public String test930(@RequestHeader("userId") String userId, @RequestHeader("profile") String profile) throws Exception {

        UserInfo userInfo = userService.queryUserInfo(Integer.valueOf(userId));
        //newUserMsgAsyncTask.execute("wxPushUser" + userInfo.getUserId(), 0, userInfo);
        newUserMsgAsyncTask.execute20210208("wxPushUser" + userInfo.getUserId(), 1, userInfo, profile);

        return "OK";
    }

    @PostMapping(value = "/testCoupon", produces = "application/json;charset=UTF-8")
    public String testCoupon(@RequestHeader("userId") String userId, @RequestHeader("profile") String profile) {

        UserInfo userInfo = userService.queryUserInfo(Integer.valueOf(userId));

        UserGroupOpenId ugoId = userGroupGzhService.getUserOpenId(profile, userInfo.getUserId());
        if (ugoId != null) {
            userInfo.setOpenId(ugoId.getOpenId());
        }

        PlatformSysInfo sysGzh = sysGzhService.getPlatformSysInfo(profile);
        WxMpKefuMessage.WxArticle wxArticle = null;

        wxArticle = new WxMpKefuMessage.WxArticle();
        wxArticle.setTitle("恭喜您，获取一张大额代金券！");
        wxArticle.setDescription("最高立减30元，点击领取>");
        wxArticle.setPicUrl("https://zktuistatic.oss-cn-shenzhen.aliyuncs.com/wxTouXiang/couponLogo.jpg"+"?"+ SysConstant.OSS_PAR_80_80);

        String accessUrl = sysGzh.getOpenMemberMenuUrl() + "?mt=1&cardBag=1";

        wxArticle.setUrl(accessUrl);

        WxMpKefuMessage testMsg = WxMpKefuMessage.NEWS().addArticle(wxArticle).toUser(userInfo.getOpenId()).build();
        try {
            WeixinServiceDL weixinService = WeixinServiceMap.getWeixinService(profile);
            weixinService.getKefuService().sendKefuMessage(testMsg);
        } catch (WxErrorException e) {
            e.printStackTrace();
        }

        return "OK";

    }

    @PostMapping(value = "/getTemplateMessage", produces = "application/json;charset=UTF-8")
    public String getTemplateMessage(@RequestHeader("userId") String userId, @RequestHeader("profile") String profile) throws Exception {

        UserInfo userInfo = userService.queryUserInfo(Integer.valueOf(userId));

        UserGroupOpenId ugoId = userGroupGzhService.getUserOpenId(profile, userInfo.getUserId());
        if (ugoId != null) {
            userInfo.setOpenId(ugoId.getOpenId());
        }

        kefuMsgExpiredRemindAsyncTask.execute("wxPushUser" + userInfo.getUserId(),profile);
        weeklyTempMsgAsyncTask.execute(userInfo, 0, profile);
        expirationReminderTempMsgAsyncTask.execute(userInfo, 0, profile);
        renewalReminderTempMsgAsyncTask.execute(userInfo, 0, profile);
        //userDailyBrandSetInfoPushAsyncTask.execute(userInfo,profile);

        PlatformSysInfo sysGzh = sysGzhService.getPlatformSysInfo(profile);

        /*WxMpTemplateMessage templateMessage1 = WxMpTemplateMessage.builder()
                // 接收者openid
                .toUser(userInfo.getOpenId())
                // 模板id
                .templateId(sysGzh.getSysGzh().getSetBrandTempId())
                // 模板跳转链接
                .url(sysGzh.getFrontDomain() + "/pages/article/editBrands.html")
                .build();
        String firstMsg1 = "为不影响您的产品体验，请尽快选择您关注的品牌。";
        String remarkMsg1 = "\uD83D\uDC49点这里马上设置";
        // 添加模板数据
        templateMessage1.addData(new WxMpTemplateData("first", firstMsg1, "#FF00FF"))
                .addData(new WxMpTemplateData("keyword1", userInfo.getNickName(), "#A9A9A9"))
                .addData(new WxMpTemplateData("keyword2", "未设置关注品牌", "#FF0000"))
                .addData(new WxMpTemplateData("remark", remarkMsg1, "#0000FF"));*/


        // 发送模板消息接口
        WxMpTemplateMessage templateMessage2 = WxMpTemplateMessage.builder()
                // 接收者openid
                .toUser(userInfo.getOpenId())
                // 模板id
                .templateId(sysGzh.getSysGzh().getCailyPaperTempId())
                // 模板跳转链接
                .url(sysGzh.getArticleListMenuUrl())
                .build();
        DailyPaperInfo dailyPaperInfo = userService.getUserDailyPaper(userInfo.getUserId());
        if (dailyPaperInfo != null) {
            String firstMsg2 = "您的数据日报\n\n退订日报请回复：86";
            String remarkMsg2 = "今天你没有发文章和视频\t\uD83D\uDC94\n\n" +
                    "点击【客户】菜单精准锁客\n" +
                    "\t\t\t\t\t\t\uD83D\uDC47\uD83D\uDC47\uD83D\uDC47";
            // 添加模板数据
            templateMessage2.addData(new WxMpTemplateData("first", firstMsg2, "#FF00FF"))
                    .addData(new WxMpTemplateData("keyword1", dailyPaperInfo.getSubTotal().toString(), "#A9A9A9"))
                    .addData(new WxMpTemplateData("keyword2", "0", "#A9A9A9"))
                    .addData(new WxMpTemplateData("keyword3", "0", "#A9A9A9"))
                    .addData(new WxMpTemplateData("remark", remarkMsg2, "#0000FF"));

            try {
                // 发送模板消息
                WeixinServiceDL weixinService = WeixinServiceMap.getWeixinService(profile);
//                weixinService.getTemplateMsgService().sendTemplateMsg(templateMessage1);
                weixinService.getTemplateMsgService().sendTemplateMsg(templateMessage2);
            } catch (WxErrorException e) {
            }
        }

        uploadTempMsgPushAsyncTask.execute(userInfo, profile,0);
        uploadTempMsgPushAsync430Task.execute(userInfo, profile,0);

        return "OK";
    }
}
